#!/opt/homebrew/bin/bash

SERVER_USER="root"
LOCAL_JAR_PATH="./drama-portal/target/drama-portal-1.0-SNAPSHOT.jar"
REMOTE_DIR="/data/java/"
# 定义键值对映射
declare -A JAR_MAP=(
    ["portal"]="../../../drama-portal/target/drama-portal-1.0-SNAPSHOT.jar"
    ["admin"]="../../../drama-admin/target/drama-admin-1.0-SNAPSHOT.jar"
)

declare -A ENV_MAP=(
    ["dev_meta"]="http://59.110.91.205:7071"
    ["prod_meta"]="http://47.113.124.224:7071"
    ["dev_ip"]="59.110.91.205"
    ["prod_ip"]="47.113.124.224"
)

# 检查是否提供了正确的参数
if [ "$#" -ne 2 ] && [ "$1" != "all" ]; then
    echo "Usage: $0 <key> <version>"
    exit 1
fi

# 获取键值
KEY="$1"
VERSION="$2"
ENVIRONMENT="$3"
env_ip_key="${ENVIRONMENT}_ip"
SERVER_IP=${SERVER_IP:-${ENV_MAP[$env_ip_key]}}

upload_jar() {
    local key="$1"
    local version="$2"
    local local_jar_path="${JAR_MAP[$key]}"

    # 确保本地JAR文件存在
    if [ ! -f "$local_jar_path" ]; then
        echo "Warning: File not found at $local_jar_path"
        return 1
    fi

    # 使用scp上传文件
    scp  "$local_jar_path" "${SERVER_USER}@${SERVER_IP}:${REMOTE_DIR}drama-$key-$version-SNAPSHOT.jar" 2>&1

    # 检查scp命令是否成功执行
    if [ $? -eq 0 ]; then
        echo "JAR file uploaded successfully to ${SERVER_USER}@${SERVER_IP}:${REMOTE_DIR}drama-$key-$version-SNAPSHOT.jar"
        return 0
    else
        echo "Failed to upload JAR file for key: $key"
        return 1
    fi
}

if [ "$KEY" = "all" ]; then
    for key in "${!JAR_MAP[@]}"; do
        if ! upload_jar "$key" "$VERSION"; then
            echo "Upload failed for key: $key"
        fi
    done
else
    if [[ -z "${JAR_MAP[$KEY]}" ]]; then
        echo "Error: Key '$KEY' not found in the [ portal,admin ]."
        exit 1
    fi

    if ! upload_jar "$KEY" "$VERSION"; then
        echo "Upload failed for key: $KEY"
        exit 1
    fi
fi